import React, { useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import { Select, DatePicker } from 'antd';
import styles from './index.less';
import _ from 'lodash';
import moment from 'moment';

import { TRDefault } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { PageLoading, DimensionalSort } from '@/components';
import { TjChart, TjCollapse } from '@/pages/ETrade/components';
import { export_json_to_excel } from '@/utils/fileExport.js';

import BaseTable from './BaseTable';
import {
  chartsMap,
  chartsMap_subpage,
  indexMap,
  Doubel_yAxis_title,
  Doubel_yAxis_serise,
  SELECT_DATA,
  tableHead,
  OPTION_KEY,
} from './helper';
import {
  _getTotalStatementEnergyPrice,
  _getPriceAverage,
  _getXAXIS,
  getNewDataSource,
  forMater,
  _getTotalLongTermStatementEnergyPrice,
  _getLongTermStatementEnergyPrice,
  formatJson,
} from './utils';
import { spotResumptionInProvince } from '../../services';
import Title from '../Title';
import { useSetState } from 'ahooks';

const defaultParams = ['是否入市', '交易单元', '日期'];
export default forwardRef(
  (
    { queryForm, queryUrlForm, stations, dimensionEnum, hasUrlData, changeSearchBtnLoading },
    ref,
  ) => {
    const [realData, setRealData] = useState([]); // 记录echars数据
    const [sumaryData, setSumaryData] = useState([]); // 概括数据
    const [tableData, setTableData] = useState([]); // 表格数据
    const [crumbsName, setCrumbsName] = useState(''); // echarts图表面包屑
    const [choseValue, setChoseValue] = useState({}); // 当前展示的echarts数据
    const [loading, setLoading] = useState(true);
    const [echartsParam, setEchartsParam] = useSetState({
      market: '',
      date: '',
      unit: '',
      timeOrder: '',
    }); //图表筛选参数
    const [param, setParam] = useState(defaultParams); //灵活聚合项
    const [error, setError] = useState('');
    const [dateTime, setDateTime] = useState(); //父维度筛选 时间
    const [filterOptions, setFilterOptions] = useState([]);

    useImperativeHandle(ref, () => ({
      onFetch,
      onExport,
    }));

    useEffect(() => {
      // getEcharsData(choseValue);
      let crum = '合计';
      // 处理合计时的面包屑-去掉合计
      if (choseValue.crumbsName) {
        const curmbsNameArr = choseValue.crumbsName.split('——');

        if (curmbsNameArr[0] === crum && curmbsNameArr.length > 1) {
          crum = curmbsNameArr.slice(1).join('——');
        } else if (dimensionEnum === 1 && hasUrlData && curmbsNameArr.length > 1) {
          // 96-场站维度的场站名称
          crum = curmbsNameArr[1];
        } else {
          crum = choseValue.crumbsName;
        }
      }
      setCrumbsName(crum);
    }, [tableData, choseValue]);

    useEffect(() => {
      if (!tableData.length) return;
      repaint();
    }, [JSON.stringify(echartsParam)]);

    useEffect(() => {
      if (!tableData.length) return;
      onFetch();
    }, [JSON.stringify(param)]);

    /** 数据处理 */
    async function onFetch() {
      setTableData([]);
      setSumaryData([]);
      changeSearchBtnLoading(true);
      const { stationIds, provinceId, tag, startDate, endDate, dimension, groupIds, pointNum } =
        queryForm;
      const params = {
        stationIds,
        provinceId,
        tag,
        startDate,
        endDate,
        dimension,
        groupIds,
        pointNum,
      };
      await Promise.all([
        onFetchData(params),
        // onFetchSumarys(params)
      ]).finally(() => changeSearchBtnLoading(false));
    }

    async function onFetchData(params) {
      setLoading(true);
      // 表格数据

      const flexibleParams = {
        flexAggrBody: {
          needTotal: true,
          operators: {
            综合电费: { total: 'sum', point: '' },
            综合电量: { total: 'sum', point: '' },
            综合电价: { total: 'custom', point: 'any' },
            中长期电费: { total: 'sum', point: '' },
            中长期电量: { total: 'sum', point: '' },
            中长期合约电价: { total: 'custom', point: 'any' },
            日前电费: { total: 'sum', point: '' },
            日前预测电量: { total: 'sum', point: '' },
            日前电价: { total: 'custom', point: 'any' },
            日前偏差电费: { total: 'sum', point: '' },
            实时电费: { total: 'sum', point: '' },
            实时电量: { total: 'sum', point: '' },
            实时电价: { total: 'custom', point: 'any' },
            实时偏差电费: { total: 'sum', point: '' },
            被动电费测算: { total: 'sum', point: '' },
            被动电价测算: { total: 'custom', point: '' },
            被动电量比例: { total: 'avg', point: '' },
            全现货测算: { total: 'sum', point: '' },
            全现货均价测算: { total: 'custom', point: '' },
            中长期仓位损益: { total: 'sum', point: '' },
            D1全合约测算: { total: 'sum', point: '' },
            D1全合约测算均价: { total: 'custom', point: '' },
            装机容量: { total: 'any', point: 'group' },
            标杆电价: { total: 'any', point: 'group' },
            是否入市: { total: 'any', point: 'group' },
          },
          order: param,
        },
        spotResumptionInProvinceBody: params,
      };
      setChoseValue({ name: '合计', flag: '合计__parent' });
      const res = await spotResumptionInProvince(flexibleParams).catch(() => setLoading(false));
      if (res?.statusCode === HttpCode.SUCCESS) {
        if (res.data && Object.keys(res.data).length > 0) {
          const data = getNewDataSource(
            res.data || [],
            flexibleParams.flexAggrBody.order,
            queryForm.pointNum,
          );
          setTableData(data);
          getFilterOptions(data);
          getSumaryData(data);
        }
      } else {
        setError(res?.message || '系统异常');
      }
      setLoading(false);
    }

    const getSumaryData = (data) => {
      const total = data[0];
      const sumaryData = [
        {
          sort: 1,
          label: '综合统计',
          income: parseFloat(total['totalStatementEnergyIncome'] / 10000).toFixed(2),
          price: parseFloat(total['totalStatementEnergyPrice']).toFixed(2),
          quantity: parseFloat(total['totalStatementQuantity']).toFixed(2),
        },
        {
          sort: 2,
          label: '中长期',
          income: parseFloat(total['totalLongTermStatementEnergyIncome'] / 10000).toFixed(2),
          price: parseFloat(total['totalLongTermStatementEnergyPrice']).toFixed(2),
          quantity: parseFloat(total['totalLongTermStatementQuantity']).toFixed(2),
        },
        {
          sort: 3,
          label: '现货',
          income: parseFloat(total['realtimeIncome'] / 10000).toFixed(2),
          price: parseFloat(total['realtimeQuantity']).toFixed(2),
          quantity: parseFloat(total['realtimePrice']).toFixed(2),
        },
      ];
      setSumaryData(sumaryData);
    };
    // async function onFetchSumarys(params) {
    //   // 概览数据

    //   const res = await querySpotResumeAnalysisOverall(params).catch(() => {});
    //   if (res?.statusCode === HttpCode.SUCCESS) {
    //     const data = res.data.filter((t) => t.label !== '现货考核');
    //     setSumaryData(data);
    //   } else {
    //     setError(res?.message || '系统异常');
    //   }
    // }

    const getExportList = (data = []) => {
      let arr = [];
      const fun = (list) => {
        list.forEach((i) => {
          arr.push(i);
          if (i?.children instanceof Array) {
            fun(i.children);
          }
        });
      };
      fun(data);
      return arr;
    };

    const onExport = () => {
      let filename = '现货复盘分析';
      if (queryForm.regions) {
        filename = `${queryForm.regions}${queryForm.startDate
          .split('-')
          .join('')}-${queryForm.endDate.split('-').join('')}`;
      }
      const params = {
        header: ['维度'],
        data: [],
        filename,
      };
      const dataFalt = getExportList(tableData);
      const filterVal = ['name'];
      tableHead?.forEach((item) => {
        params.header.push(item.name);
        filterVal.push(item.field);
      });
      params.data = formatJson(filterVal, dataFalt);
      export_json_to_excel(params);
    };

    /** methods */

    //控制日历可选范围
    const disabledDate = (current) => {
      const _date = dateTime;
      return (current && current < _date[0].startOf('day')) || current > _date[1].endOf('day');
    };

    //获取各项筛选框数据源
    const getFilterOptions = (data, _echartsParam = {}, oIndex = -1) => {
      if (!data.length) return;

      const _params = {
        ...echartsParam,
        ..._echartsParam,
      };
      const filterData = _.cloneDeep(data).splice(1);
      const _filterOptions = [];
      (function reduce(data, index = 0) {
        const options = [];
        data.forEach((t, i) => {
          //判断是否为最后一个维度   ps:最后一个维度无需下拉选项
          if (!t?.children?.length) return;
          options.push(t.title);
          //取默认首项
          if (oIndex < index && i === 0) {
            _params[OPTION_KEY[param[index]]] = t.title;
          }
          //取对应维度子项
          if (t.title === _params?.[OPTION_KEY[param[index]]]) {
            setEchartsParam({
              [OPTION_KEY[param[index]]]: t.title,
            });
            reduce(t.children, index + 1);
          }
        });

        _filterOptions[index] = options;
      })(filterData);
      setFilterOptions(_filterOptions);

      //处理日期可选区间
      const dateList = _filterOptions[param.indexOf('日期')];
      const _startDate = dateList?.[0];
      const _endDate = dateList?.[dateList.length - 1];
      const _datetime = [moment(_startDate), moment(_endDate)];
      setDateTime(_datetime);
    };

    //根据父维度 筛选出图表所需数据  return:最后一个维度数组
    const _getFilterXAXIS = (data, arr) => {
      const _echartsParam = _.cloneDeep(echartsParam);
      //取最后一个维度 第一行数据
      const recursion = (item, index) => {
        const _item = [];
        item.forEach((t) => {
          if (t.title === '合计') return;
          _item.push(t);
        });
        let _temp = [];
        //如果已经是最后一个维度
        if (arr.length - 1 <= index) {
          return _item;
        }
        _item.forEach((t) => {
          t.title === _echartsParam[OPTION_KEY[arr[index]]] &&
            (_temp = recursion(t.children, index + 1));
        });
        return _temp;
      };
      return recursion(data, 0);
    };

    //根据筛选参数 重绘图表
    const repaint = async () => {
      const echarsData = _getFilterXAXIS(tableData, param);
      const XAXIS = echarsData.map((t) => t.title);
      const dataMap = {};
      new Set(Object.values(chartsMap).flat()).map((t) => {
        if (t.includes('_')) return; //在下方计算
        dataMap[t] = forMater(echarsData, t);
      });
      //计算
      dataMap._totalLongTermStatementEnergyPrice = _getLongTermStatementEnergyPrice(echarsData);
      dataMap._longTermStatementEnergyPrice = _getTotalLongTermStatementEnergyPrice(echarsData);
      setRealData({
        ...dataMap,
        XAXIS,
      });
    };

    /**图表配置*/
    const getChartOption = ([title, data], dataSource) => {
      const chartData = [],
        _yAxis = [{ type: 'value' }];
      dataSource.XAXIS.map((x, i) => {
        const temp = {};
        data.map((t) => {
          const a = t.split('_');
          //屏蔽同名 不同系列名
          if (a[0] && a[1]) {
            temp[t] = dataSource[a[0]][i];
            return;
          }
          temp[t] = dataSource[t][i];
        });
        chartData.push({
          ...temp,
          XAXIS: x,
        });
      });
      if (Doubel_yAxis_title.includes(title)) {
        _yAxis.push({
          type: 'value',
          splitLine: { show: false },
        });
      }
      const _series = data.map((t) => {
        const { props, ...others } = _.cloneDeep(indexMap[t]);
        if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
          props.yAxisIndex = 1;
        }
        return {
          dataIndex: t,
          props,
          ...others,
        };
      });

      return {
        grid: { top: 20, left: 48, right: 48, bottom: 50 },
        series: _series,
        dataset: {
          source: chartData,
          dimensions: ['XAXIS', ...data],
        },
        tooltip: {},
        legend: {},
        xAxis: [{ type: 'category' }],
        yAxis: _yAxis,
      };
    };

    /**图表筛选 */
    const _polymerize = (options) => {
      setParam(['是否入市', ...options]);
    };

    const onFilterChange = (value, index, key) => {
      const _echartsParam = {
        [key]: value,
      };
      getFilterOptions(tableData, _echartsParam, index);
    };

    /** render */
    const _getEchartsData = () => {
      const loopData = !hasUrlData
        ? Object.entries(chartsMap)
        : Object.entries(chartsMap_subpage).map((t) => [t[0], Object.keys(t[1])]);
      if (!realData?.XAXIS) return <TRDefault type={'empty'} />;
      return (
        <div className={styles.chartsRender}>
          {loopData.map((t, i) => {
            return (
              <div
                key={i}
                style={{
                  height: `calc(${Math.floor(100 / loopData.length)}%)`,
                  minHeight: 204,
                }}
              >
                <div className={styles.chartTitle}>{t[0]}</div>
                <div style={{ height: `calc(100% - 36px)` }}>
                  <TjChart option={getChartOption(t, realData)} />
                </div>
              </div>
            );
          })}
        </div>
      );
    };

    if (loading) return <PageLoading />;
    if (error) return <TRDefault type="error" message={error} />;
    if (!tableData.length) return <TRDefault type={'empty'} />;
    return (
      <>
        <div className={styles.box}>
          <Title data={sumaryData} />
        </div>
        <div className={styles.content}>
          <TjCollapse
            leftStyles={{ padding: '0 20px 24px 0' }}
            rightStyles={{ padding: '20px 24px', width: '50%' }}
            left={
              <>
                <div className={styles.sort}>
                  <DimensionalSort
                    optionsArray={SELECT_DATA.filter((t) => t !== '是否入市')}
                    option={param.filter((t) => t !== '是否入市')}
                    onClick={_polymerize}
                  />
                </div>
                <div className={styles.tableScroll}>
                  <BaseTable
                    tableData={tableData}
                    tableHead={tableHead}
                    stations={stations}
                    queryForm={queryForm}
                    queryUrlForm={queryUrlForm}
                  />
                </div>
              </>
            }
            right={
              <>
                <div className={styles.filter_group}>
                  <div className={styles.flex}>
                    {param.map((t, i) => {
                      if (t === '是否入市' && param[param.length - 1] !== '是否入市') {
                        {
                          return (
                            <Select
                              key={i}
                              className={styles.filter_unit}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              showSearch
                              placeholder="选择入市配置"
                              onChange={(e) => {
                                onFilterChange(e, i, 'market');
                              }}
                              value={echartsParam.market}
                              options={filterOptions[i].map((t) => ({
                                label: t,
                                value: t,
                              }))}
                            />
                          );
                        }
                      }
                      if (t === '交易单元' && param[param.length - 1] !== '交易单元') {
                        {
                          return (
                            <Select
                              key={i}
                              className={styles.filter_unit}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              showSearch
                              placeholder="选择交易单元"
                              onChange={(e) => {
                                onFilterChange(e, i, 'unit');
                              }}
                              value={echartsParam.unit}
                              options={filterOptions[i].map((t) => ({
                                label: t,
                                value: t,
                              }))}
                              filterOption={(input, option) => {
                                return (option?.label).toLowerCase().includes(input.toLowerCase());
                              }}
                            />
                          );
                        }
                      }
                      if (t === '日期' && param[param.length - 1] !== '日期') {
                        {
                          return (
                            <DatePicker
                              key={i}
                              onChange={(e) => {
                                onFilterChange(e.format('YYYYMMDD'), i, 'date');
                              }}
                              inputReadOnly
                              allowClear={false}
                              className={styles.filter_date}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              value={moment(echartsParam.date)}
                              format={'YYYYMMDD'}
                              disabledDate={disabledDate}
                            />
                          );
                        }
                      }
                      if (t === '时点' && param[param.length - 1] !== '时点') {
                        {
                          return (
                            <Select
                              key={i}
                              className={styles.filter_point}
                              style={{ marginLeft: i === 0 ? 0 : 16 }}
                              placeholder="选择时点"
                              onChange={(e) => {
                                onFilterChange(e, i, 'point');
                              }}
                              value={echartsParam.timeOrder}
                              options={filterOptions[i].map((t) => ({
                                label: t,
                                value: t,
                              }))}
                            />
                          );
                        }
                      }
                    })}
                  </div>
                </div>
                {/* <div className={styles.title}>{crumbsName}</div> */}
                {_getEchartsData()}
              </>
            }
          />
        </div>
      </>
    );
  },
);
